﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;
using ClassLibrary;

namespace OmegapointWeb.ajax
{
    public partial class upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string userId = Request["Id"].ToString();

                if (!(Request.Files == null || Request.Files.Count <= 0))
                {
                    foreach (string f in Request.Files.AllKeys)
                    {
                        HttpPostedFile file = Request.Files[f];
                        string tmpF = file.FileName.ToLower();

                        if (!(tmpF.Contains(".jpg") || tmpF.Contains(".jpeg") || tmpF.Contains(".png") || tmpF.Contains(".gif")))
                        {
                            Response.Write("FormatException");
                            break;
                        }

                        Guid newImageId = Guid.NewGuid();

                        string extension = "";
                        int index = 0;
                        for (int i = (file.FileName.Length - 1); i >= 0; i--)
                        {
                            if (file.FileName.ToCharArray()[i] == '.')
                            {
                                index = i++;
                                break;
                            }
                        }

                        string dir = ConfigurationManager.AppSettings["ImagesDir"].ToString() + userId;
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        string FilePath = dir + "\\" + newImageId + file.FileName.Substring(index);
                        ImageDataController.CreateEmptyImageData(newImageId.ToString(), userId, FilePath);
                        file.SaveAs(FilePath);
                        LogWriter.Print("Upload new Image by WebUser: " + userId, LogLevel.LOG);
                        LogWriter.Print("upload() -> Saving file to: " + FilePath, LogLevel.LOG);
                    }
                }
            }
            catch (Exception exc)
            {
                LogWriter.Print("Exception submitFile->PageLoad() " + exc, LogLevel.EXCEPTION);
            }
        }
    }
}